import { BaseComponent } from "components/common/base-component";
import { ShoppingService } from "mobile/services/shoppingService";
import { ImageService } from "maishu-services-sdk";
import { component } from "components/common/component";
import React = require("react");
import * as ui from "maishu-ui-toolkit";

export interface Props {
    showSecondLevel?: boolean,
    showIcon?: boolean,
}

export interface State {
    categories?: Category[],
}

@component()
export class Categories extends BaseComponent<Props, State> {
    private shopping: ShoppingService;
    private imageService: ImageService;

    constructor(props) {
        super(props);
        this.state = {};

        this.shopping = this.createService(ShoppingService);
        this.imageService = this.createService(ImageService);

    }

    componentDidMount() {
        this.shopping.categories().then(categories => {
            this.setState({ categories });
        })
    }

    render() {
        var result = this.props.showIcon ?
            this.renderWithIcons() : this.renderWithoutIcons();

        return result;
    }

    renderWithIcons() {
        var categories = this.state.categories;
        return <div className="categories-control clearfix">
            {categories ? categories.map(item => (
                <a key={item.Id} href={`#home_productList?categoryId=${item.Id}`} className="col-xs-4">
                    <img src={this.imageService.imageSource(item.ImagePath, 100, 100)} className="img-responsive"
                        ref={(e: HTMLImageElement) => e ? ui.renderImage(e, { imageSize: { width: 100, height: 100 } }) : null} />
                    <span className="mini interception">{item.Name}</span>
                </a>
            )) : null}
        </div>
    }
    renderWithoutIcons() {
        var categories = this.state.categories;
        categories = (categories || []).sort((a, b) => {
            return (a.SortNumber || 0) - (b.SortNumber || 0);
        });
        return <div className="categories-control clearfix">
            {categories.map((item, i) => (
                <div key={item.Id || i} className="col-xs-6">
                    <div className="well">
                        <a href={`#home_productList?categoryId=${item.Id}`}>
                            <span className="mini interception">{item.Name}</span>
                        </a>
                    </div>
                </div>
            ))}
        </div>
    }
}